//
//  AccoutProductsViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-6-22.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "AccoutProductsViewController.h"
#import "NYMemberCenterDataManager.h"
#import "NYAccountProduct.h"
#import "AccountProductTableCell.h"
#import "JSON.h"
#import "NSDate+RYAdditions.h"
#import "AccountProductDetailViewController.h"

static NSInteger kNumOfPage = 10000;
static NSInteger kInitPageNum = 1;
static NSInteger kCurrentPageNum = 1;

@interface AccoutProductsViewController ()

@end

@implementation AccoutProductsViewController

@synthesize productTypeId;
@synthesize accountProsTableView;
@synthesize moreView,products;
@synthesize placeHolderImageView;

- (MoreView *)moreView
{
    if(nil == moreView)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"MoreView" owner:self options:nil];
        moreView = [[nibs lastObject] retain];
        moreView.delegate = self;
    }
    return moreView;
}

#pragma mark - Public methods
- (void)callServerToGetAccountProductsList:(NSString *)accountId
                                   pageNo:(NSString *)pageNo
                                 pageSize:(NSString *)pageSize
                               updateTime:(NSString *)updateTime
{
    NSString *suburl = [NSString stringWithFormat:kAccountProductsUrl,@"jsonp",accountId,pageNo,pageSize,updateTime];
    suburl = [suburl stringByAppendingString:@"app000026"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
}

- (void)callServerToGetAccountProducts
{
    NSString *accountId = nil;
    if(nil == [NYMemberCenterDataManager sharedManager].loginMember.accountId)
        accountId = @"";
    else
        accountId = [NYMemberCenterDataManager sharedManager].loginMember.accountId;
    
    
    [self callServerToGetAccountProductsList:accountId pageNo:[NSString stringWithFormat:@"%d",kCurrentPageNum] pageSize:[NSString stringWithFormat:@"%d",kNumOfPage] updateTime:@""];
}

- (void)refreshProductsList
{
    kCurrentPageNum = kInitPageNum;
    [self callServerToGetAccountProducts];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle:@"已投产品"];
    
    [self refreshProductsList];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        self.view = nil;
        self.accountProsTableView = nil;
        self.moreView = nil;
        self.placeHolderImageView = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.accountProsTableView = nil;
    self.placeHolderImageView = nil;
    self.moreView = nil;
}

- (void)dealloc
{
    [placeHolderImageView release];
    [moreView release];
    [products release];
    [accountProsTableView release];
    [productTypeId release];
    [super dealloc];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.products.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    AccountProductTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if(nil == cell)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"AccountProductTableCell" owner:self options:nil];
        cell = [nibs lastObject];
        UIImageView *bgView = [[UIImageView alloc] initWithFrame:cell.bounds];
        bgView.image = [UIImage imageNamed:@"bg_selection@2x.png"];
        cell.selectedBackgroundView = bgView;
        [bgView release];
    }
    NYAccountProduct *nyap = [self.products objectAtIndex:indexPath.row];
    cell.nameLabel.text = nyap.product_name;
    cell.startDateLabel.text = nyap.establish_day;
    cell.endDateLabel.text = nyap.terminate_day;
    if([nyap.ishave_newmessage isEqualToString:@"1"])
        cell.markImageView.hidden = NO;
    else
        cell.markImageView.hidden = YES;
    
    NSDate *currentDate = [NSDate date];
    NSString *currentDateString = [NSDate dateToStringByFormat:@"yyyy-MM-dd" date:currentDate];
    cell.currentDateLabel.text = currentDateString;
    //计算进度条的长度
    CGFloat width = 0;
    if(nil == nyap.terminate_day || [nyap.terminate_day isEqualToString:@""])
    {
        cell.endDateLabel.hidden = YES;
        cell.endLabel.hidden = YES;
        width = cell.bgProgressImageView.frame.size.width;
    }
    else
    {
        cell.endDateLabel.hidden = NO;
        cell.endLabel.hidden = NO;
        NSDate *startDate = [NSDate dateFromStringByFormat:@"yyyy-MM-dd" string:nyap.establish_day];
        NSDate *endDate = [NSDate dateFromStringByFormat:@"yyyy-MM-dd" string:nyap.terminate_day];
        
        NSTimeInterval wholeGap = [endDate timeIntervalSinceDate:startDate];
        NSTimeInterval gap = [currentDate timeIntervalSinceDate:startDate];
        //当前时间超过截止时间
        if(gap > wholeGap)
            gap = wholeGap;
        //当前时间没到开始时间
        if(gap < 0)
            gap = 0;
        if(wholeGap != 0)
            width = gap/wholeGap*cell.bgProgressImageView.frame.size.width;
    }

    UIImage *image = [UIImage imageNamed:@"progress.png"];
    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(0, 4.f, 0, 4.f)];
    CGRect rect = cell.progressImageView.frame;
    rect.size.width = width;
    cell.progressImageView.frame = rect;
    cell.progressImageView.image = image;
    //计算当前日期的显示位置
    CGFloat x = cell.progressImageView.frame.origin.x+cell.progressImageView.frame.size.width;
    cell.currentDateLabel.center = CGPointMake(x, cell.currentDateLabel.center.y);
    
    return cell;
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kAccountProductTableCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AccountProductDetailViewController *apdvc = [[AccountProductDetailViewController alloc] initWithNibName:@"AccountProductDetailViewController" bundle:nil];
    apdvc.accountProduct = [self.products objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:apdvc animated:YES];
    [apdvc release];
}

#pragma mark - MoreViewDelegate method
- (void)didMoreViewClicked
{
    ++kCurrentPageNum;
    [self callServerToGetAccountProducts];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        if(kCurrentPageNum == kInitPageNum)
            self.products = [NSMutableArray array];
        NSArray *array = [dict objectForKey:@"list"];
        for(NSDictionary *dict in array)
        {
            NYAccountProduct *nyap = [[NYAccountProduct alloc] init];
            for(NSString *key in [dict allKeys])
            {
                @try {
                    [nyap setValue:[dict objectForKey:key] forKey:key];
                }
                @catch (NSException *exception) {
                    NSLog(@"试图添加不存在的key: %@到NYAccountProduct实例中.",key);
                }
            }
            [self.products addObject:nyap];
            [nyap release];
        }
        
        if(array.count == kNumOfPage)
            self.accountProsTableView.tableFooterView = self.moreView;
        else
            self.accountProsTableView.tableFooterView = nil;
        
        //重新加载产品列表
        [self.accountProsTableView reloadData];
    }
    else
    {
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
        self.accountProsTableView.tableFooterView = nil;
    }
    if(self.products.count == 0)
    {
        self.placeHolderImageView.image = [UIImage imageNamed:@"nodata.png"];
        self.placeHolderImageView.hidden = NO;
        self.accountProsTableView.hidden = YES;
    }
    else
    {
        self.placeHolderImageView.hidden = YES;
        self.accountProsTableView.hidden = NO;
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    if(self.products.count == 0)
    {
        self.placeHolderImageView.image = [UIImage imageNamed:@"nodata.png"];
        self.placeHolderImageView.hidden = NO;
        self.accountProsTableView.hidden = YES;
    }
    else
    {
        self.placeHolderImageView.hidden = YES;
        self.accountProsTableView.hidden = NO;
    }
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

@end
